

import shlex
import time
import sys
import os
import argparse
import ssh_paramiko
from log import LoggerLog
logger = LoggerLog("ssh").get_log


def bash(cmd):
    """
    执行执行bash命令
    """
    logger.info(cmd)
    return shlex.os.system(cmd)


def packaging(type):
    """
    编译打包
    """
    if type == None:
        print("pass")


def parse_args():

    content = """结合jenkins和cmdb接口来完成发布流程
        """
    parser = argparse.ArgumentParser(
        usage="jenkins发布辅助工具",
        description=content,
        add_help=False,
        formatter_class=lambda prog: argparse.RawTextHelpFormatter(
            prog, max_help_position=50)
    )
    parser.add_argument("--help",
                        action="help",
                        help="查看帮助信息")
    parser.add_argument("-t", "--type",
                        default=None,
                        help="java,vue,php,html,file...")

    parser.add_argument("--compile",
                        action="store_true",
                        help="编译")

    parser.add_argument("--custom_pkg",
                        help="自定义打包命令")
    parser.add_argument('-h', '--host',
                        help='主机地址')

    parser.add_argument('-j', '--job',
                        help='项目名')
    parser.add_argument('-g', '--git',
                        help='git链接地址')

    parser.add_argument("--action",
                        help="操作选项:发布、仅打包、重启、回滚、开服、合服")
    args = parser.parse_args()
    return args


def compressed(job_dir, job):
    logger.info("压缩文件")
    bash("cd %s   && tar zcf %s.tar.gz *" % (job_dir, job))


def sftp(pystr, local_file, remote_dir):
    res = "%s -t put --local_file %s --remote_dir %s" % (
        pystr, local_file, remote_dir)
    bash(res)


def rt_exec(pystr, cmd):
    res = "%s  --run%s" % (pystr, cmd)
    bash(res)


if __name__ == '__main__':
    now = time.time()
    start_time = time.strftime("%Y%m%d%H%M", time.localtime(now))
    if len(sys.argv) == 1:
        """ 如果没有传参则打印帮助信息 """
        sys.argv.append("--help")
        args = parse_args()
        sys.exit(1)
    args = parse_args()  # 获取参数

    ### 变量 ###
    workspace = "/opt/application/tjenkins-data/workspace"
    job_dir = os.path.join(workspace, args.job)
    tar_file = os.path.join(job_dir, args.job + ".tar.gz")
    cmd = "python3 / opt/scripts/dap/ssh_paramiko.py -h % s - uroot - k / opt/.keys/TzAdminManageKey-20200810.pem - P22" % args.host

    compressed(job_dir, args.job)  # 压缩

    sftp(cmd, tar_file, "/tmp")  # 上传

    rt_exec(cmd, "[ -d /opt/dtetl/etljobs ] || mkdir -p /opt/dtetl/etljobs")
    rt_exec(cmd, "tar zxf /tmp/%s.tar.gz -C /opt/dtetl/etljobs" % (args.job))
    # 解压

    end_time = time.strftime("%Y%m%d%H%M", time.localtime(now))
    print(start_time, end_time)
